package net.blank.timerUtl
{
	import flash.utils.Dictionary;
	
	import net.blank.pool.Pool;
	
	/**
	 * 公用计时器管理器
	 * @author blank
	 * 
	 */
	public class PublicTimerManager
	{
		/**
		 * 在对象池中的别名
		 */
		private const POOL_NAME:String="public_timer_pool";
		
		/**
		 * 计时器集合
		 */
		private var timers:Dictionary=new Dictionary();
		
		/**
		 * 添加回调函数
		 */
		public function addFunc(interval:int, func:Function, args:Array=null):PublicTimer{
			var timer:PublicTimer;
			if(interval in timers){
				timer=timers[interval];
			}else{
				timer=Pool.restoreObj(POOL_NAME);
				if(!timer){
					timer=new PublicTimer(interval);
				}else{
					timer.delay=interval;
				}
			}
			
			if(timer.addFunc(func,args)){
				return timer;
			}
			
			return null;
		}
		
		/**
		 * 移除回调函数()
		 * @param timer
		 * @param func
		 * 
		 */
		public function removeFunc(timer:PublicTimer,func:Function):void{
			if(timer){
				timer.removeFunc(func);
				if(timer.numFunc == 0){
					/*存入对象池*/
					timer.reset();
					Pool.storeObj(timer,POOL_NAME);
					
					delete timers[timer.delay];
				}
			}
		}
		
		/**
		 * 移除回调函数
		 * @param func
		 * 
		 */
		public function removeFuncByInterval(interval:int, func:Function):void{
			var timer:PublicTimer=timers[interval];
			removeFunc(timer,func);
		}
		
		/**
		 * 静态实例
		 */
		private static var $instance:PublicTimerManager=new PublicTimerManager();
		
		/**
		 * 添加回调函数
		 */
		public static function addFunc(interval:int, func:Function, args:Array=null):PublicTimer{
			return $instance.addFunc(interval,func,args);
		}
		
		/**
		 * 移除回调函数
		 * @param func
		 * 
		 */
		public static function removeFunc(interval:int, func:Function):void{
			return $instance.removeFuncByInterval(interval,func);
		}
	}
}